package pri.damai.xiaowu.common.log.trace.dubbo;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import pri.damai.xiaowu.common.log.trace.ThreadMdcUtil;

import static pri.damai.xiaowu.common.core.constant.TraceConstant.TRACE_ID;

/**
 * 消费者端的链路追踪拦截器
 * @Desc
 * @Author DaMai
 * @Date 2021/5/26 9:32
 * 但行好事，莫问前程。
 */
@Activate(group = {CommonConstants.CONSUMER})
public class ConsumerRpcTraceFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        //如果MDC上下文有追踪ID，则原样传递给provider端
        String traceId = ThreadMdcUtil.getTraceId();
        if (StringUtils.isNotEmpty(traceId)) {
            RpcContext.getContext().setAttachment(TRACE_ID, traceId);
        }
        return invoker.invoke(invocation);
    }

}
